// pages/category/category.js
import {
  getCategory,
  getSubcategory,
  getCategoryDetail  
} from '../../service/category.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories: [],
    categoryData: {},
    currentIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getCategory();
  },

  // 请求分类数据
  _getCategory() {
    getCategory().then(res => {
      // 1. 获取 categories
      const categories = res.data.data.category.list;

      // 2. 初始化每个类别的子数据
      const categoryData = {};
      for (let i = 0; i < categories.length; i++) {
        categoryData[i] = {
          subcategories: [],
          categoryDetail: [],
        }
      }

      // 3. 修改 data 中的数据
      this.setData({
        categories: categories,
        categoryData: categoryData
      })

      // 4. 请求第一个类别的数据
      this._getSubcategory(0);

      // 5. 请求第一个类别的详情数据
      this._getCategoryDetail(0);
    })
  },

  _getSubcategory(currentIndex) {
    // 1. 获取对应的 maitkey
    const maitKey = this.data.categories[currentIndex].maitKey;
    getSubcategory(maitKey).then(res => {
      const tempCategoryData = this.data.categoryData;
      tempCategoryData[currentIndex].subcategories = res.data.data.list;
      this.setData({
        categoryData: tempCategoryData,
      })
    })
  },

  _getCategoryDetail(currentIndex) {
    const miniWallKey = this.data.categories[currentIndex].miniWallkey;
    this._getRealCategoryDetail(currentIndex, miniWallKey, "pop");
  },

  _getRealCategoryDetail(index, miniWallKey, type) {
    getCategoryDetail(miniWallKey, type).then(res => {
      const categoryData = this.data.categoryData;
      categoryData[index].categoryDetail = res.data;
      this.setData({
        categoryData: categoryData
      })
    })
  },
  menuClick(e) {
    const currentIndex = e.detail.currentIndex;
    this.setData({
      currentIndex: currentIndex,
    })
    // 请求对应的 currentIndex 的数据
    this._getSubcategory(currentIndex);
    this._getCategoryDetail(currentIndex);
  }

})